package com.oreilly.ez.service.impl;

import com.oreilly.ez.entity.Person;
import com.oreilly.ez.repo.PersonRepo;
import com.oreilly.ez.service.PersonService;
import com.oreilly.ez.util.CloneUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = "person")
public class PersonServiceImpl  implements PersonService{


    @Autowired
    private PersonRepo personRepo;

    @Override
    @CachePut(value = "person", key = "#item.sid")
    public Person save(Person item) {

        //判断是否要update
        Integer sid = item.getSid();
        if(sid != null){
            Person dbItem = personRepo.getOne(sid);

            CloneUtils.copyProperties(item, dbItem);
            CloneUtils.copyProperties(dbItem, item);

        }

        Person p = personRepo.save(item);
        System.out.println("cache p = " + p);
        return p;



    }

    @Override
    @CacheEvict(value = "person", key = "#sid")
    public void remove(Integer sid) {

        System.out.println("remove cache sid = " + sid);
        personRepo.deleteById(sid);
    }

    @Override
    @Cacheable(value = "person", key = "#sid")
    public Person findOne(Integer sid) {

        Person p = personRepo.findById(sid).get();
        System.out.println("findOne cache p = " + p);
        return p;
    }

    @Override
    @Cacheable(value = "personList")
    public Page<Person> find(Person person, Pageable pageable) {

        return personRepo.findAll(pageable);
    }
}
